package dominioDAO;

import hbt.HibernateDAO;
import hbt.HibernateUtil;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import dominioEntity.Cliente;
import dominioTO.ClienteTO;


// Cliente lado Servidor DAO (Persistencia)

public class ClienteDao{
	private static ClienteDao instancia ;
	private static SessionFactory sf;
	private static Session session;
	
	public static ClienteDao getInstancia() {
		if(instancia == null){
			instancia = new ClienteDao();
		} 
		return instancia;
	}
	public ClienteDao()
	{
		sf = HibernateUtil.getSessionFactory();
	}
	
	protected Session getSession(){
		if(session == null || !session.isOpen()){
			session = sf.openSession();
		}
		return session;
	}
	

	public void persistirCliente(List<ClienteTO> list) throws RemoteException
	{		
		List<Cliente> cli = new ArrayList<Cliente>();
		for(ClienteTO dto : list){
			Cliente aux = new Cliente ();
			aux.setCuit(dto.getCuit());
			aux.setRazonSocial(dto.getRazonSocial());
			aux.setFechaAlta(dto.getFechaAlta());
			aux.setDescuentos(dto.getDescuentos());
			aux.setRespInscripto(dto.isRespInscripto());
			aux.setIngBrutos(dto.getIngBrutos());
			aux.setCondPago(dto.getCondPago());
			aux.setEstado(dto.isEstado());
			cli.add(aux);
		}
		HibernateDAO.getInstancia().persistList(cli);			
	}
	
	@SuppressWarnings("unchecked")
	public ClienteTO buscarCliente(String cuit)
	{
		Session session = sf.openSession();
		String sentencia = "from Cliente c where c.cuit=?";
		
		List<Cliente> cli = (List<Cliente>) session.createQuery(sentencia).setString(0, cuit).list();
	
		if(cli.isEmpty())
		{
			return null;	
		}
		return cli.get(0).getDTO();
	}
}
